package com.daogu.fuelcard.service.impl;

import com.daogu.fuelcard.dao.UserMapper;
import com.daogu.fuelcard.entity.User;
import com.daogu.fuelcard.service.UserService;
import com.daogu.fuelcard.utils.Md5Utils;
import com.daogu.fuelcard.utils.Result;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public Result<PageInfo<User>> getUserList(Integer pageNum,Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<User> userList = userMapper.getUserList();
        PageInfo<User> userPageInfo = new PageInfo<>(userList);
        return Result.accept(userPageInfo);
    }

    @Override
    public void insertUser(User user) {
        user.setPassword(Md5Utils.getMd5(user.getPassword()));
        userMapper.insertUser(user);
    }


    @Override
    public Boolean checkLogin(String userName, String inputPassword, HttpServletResponse response) {
        User user = userMapper.findUserByUsername(userName); // 通过用户名查找用户
        if (user == null) {
            return false; // 用户不存在
        }
        String encryptedInputPassword = DigestUtils.md5Hex(inputPassword); // 对输入的密码进行MD5加密

        if (user.getPassword().equals(encryptedInputPassword)) { // 比较加密后的密码
            // 密码匹配
            String randomKey = DigestUtils.md5Hex(userName + System.currentTimeMillis()); // 生成唯一的随机key
            redisTemplate.opsForValue().set(randomKey, "loggedIn", 12, TimeUnit.HOURS); // 将随机key存储到Redis中，有效期12小时
            Cookie loginCookie = new Cookie("token", randomKey); // 创建cookie
            loginCookie.setMaxAge((int) TimeUnit.HOURS.toSeconds(12)); // 设置cookie的最大年龄为12小时
            loginCookie.setHttpOnly(true); // 增加安全性，防止通过客户端脚本访问cookie
            loginCookie.setPath("/"); // 设置cookie的路径
            response.addCookie(loginCookie); // 添加cookie到响应中
            return true;
        } else {
            return false;
        }
    }
}
